<template>
  <div class="container">
    <div class="top-container">
      <el-button type="primary" @click="handleAddClick">添加配送点</el-button>
    </div>
    <el-table v-loading="isLoading" :data="deliveryPoints" border>
      <el-table-column label="ID" prop="id"/>
      <el-table-column label="名称" prop="name"/>
      <el-table-column label="经度" prop="longitude"/>
      <el-table-column label="纬度" prop="latitude"/>
      <el-table-column label="地图显示名称" prop="dibiao"/>
      <el-table-column label="地址" prop="address"/>
      <el-table-column label="距离" prop="distance"/>
      <el-table-column label="出餐中心" prop="mealcentername"/>
      <el-table-column label="操作">
        <template #default="{row}">
          <el-button :icon="Edit" link type="primary" @click="handleEditClick(row.id)">修改</el-button>
          <el-popconfirm title="是否确定删除？" @confirm="handleDeleteConfirm(row.id)">
            <template #reference>
              <el-button :icon="Delete" link type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <delivery-point-dialog v-model="isAddDialogShow" @success="handleDialogSuccess"/>
    <delivery-point-dialog :id="idToEdit" v-model="isEditDialogShow" @success="handleDialogSuccess"/>
  </div>
</template>
<script lang="ts" setup>
import {ref} from "vue"
import {ElMessage} from "element-plus";
import {Delete, Edit} from "@element-plus/icons-vue"
import {DeliveryPointResponse} from "@/api/types/deliveryPoint";
import {deleteDeliveryPointById, getDeliveryPoints} from "@/api/deliveryPoint";
import DeliveryPointDialog from "@/components/dialog/DeliveryPointDialog.vue";

const isAddDialogShow = ref(false)
const isEditDialogShow = ref(false)
const deliveryPoints = ref<DeliveryPointResponse[]>([])
const idToEdit = ref<number | undefined>()
const isLoading = ref(false)

async function getData() {
  if (isLoading.value == false) {
    isLoading.value = true
  }
  const {result} = await getDeliveryPoints()
  if (result !== undefined) {
    deliveryPoints.value = result
    isLoading.value = false
  }
}

getData()

function handleAddClick() {
  isAddDialogShow.value = true
}

function handleEditClick(id: number) {
  idToEdit.value = id
  isEditDialogShow.value = true
}

async function handleDeleteConfirm(id: number) {
  try {
    const {result} = await deleteDeliveryPointById(id)
    if (result !== undefined) {
      if (result) {
        ElMessage.success('删除成功');
        await getData()
      } else {
        ElMessage.error('删除失败');
      }
    }
  } catch (error) {
    ElMessage.error('删除失败');
  }
}

async function handleDialogSuccess() {
  await getData()
}
</script>
<style lang="scss" scoped>
.container {
  padding: 20px;
  background-color: white;

  .top-container {
    margin-bottom: 20px;
  }
}
</style>
